package models

import (
	"os"
	"path/filepath"

	"github.com/astaxie/beego"
	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/orm"
	_ "github.com/go-sql-driver/mysql"

	"github.com/astaxie/beego/logs"
)

// 数据库连接初始化
func Init() {
	dbURL, err := getDBUrl()
	if err != nil {
		beego.Error("Error on parse database config, %s", err.Error())
		os.Exit(1)
	}

	orm.RegisterDataBase("default", "mysql", dbURL)

	err = orm.RunSyncdb("default", false, true)
	if err != nil {
		beego.Error("Error on run database, %s", err.Error())
	}
	orm.Debug = true
}

//返回带前缀的表名
func TableName(str string) string {
	appConf, err := config.NewConfig("ini", "conf/app.conf")
	if err != nil {
		panic(err)
	}
	return appConf.String("database::db_prefix") + str
}

func getDBUrl() (string, error) {
	mysqlConfigPath := filepath.Join(beego.AppPath, "conf", "mysql.ini")
	mysqlConfig, err := config.NewConfig("ini", mysqlConfigPath)
	if err != nil {
		beego.Error("new mysql config error", err.Error())
		return "", err
	}

	envRunMode := os.Getenv("CPS_RUNMODE")
	logs.Info("cps exit...")
	if envRunMode == "" {
		envRunMode = beego.DEV
	}

	username := mysqlConfig.String(envRunMode + "::username")
	password := mysqlConfig.String(envRunMode + "::password")
	protocol := mysqlConfig.String(envRunMode + "::protocol")
	ip := mysqlConfig.String(envRunMode + "::ip")
	port := mysqlConfig.String(envRunMode + "::port")
	dbname := mysqlConfig.String(envRunMode + "::dbname")
	charset := mysqlConfig.String(envRunMode + "::charset")

	dbURL := username + ":" + password + "@" + protocol + "(" + ip + ":" + port + ")" + "/" + dbname + "?charset=" + charset

	return dbURL, nil
}
